<template>
  <BasicDrawer 
    v-bind="$attrs" 
    @register="registerDrawer" 
    title="套餐权限配置" 
    width="650px" 
    destroyOnClose 
    showFooter
  >
    <BasicForm @register="registerForm"/>
    <BasicTree
      ref="treeRef"
      checkable
      toolbar
      :treeData="treeData"
      :checkedKeys="checkedKeys"
      :expandedKeys="allTreeKeys"
      :selectedKeys="selectedKeys"
      :checkStrictly="true"
      :clickRowToExpand="false"
      search
      title="所拥有的功能"
      @check="onCheck">
      <template #title={slotTitle,ruleFlag}>
        {{ slotTitle }}
        <Icon v-if="ruleFlag" icon="ant-design:align-left-outlined" style="margin-left:5px;color: red;"></Icon>
      </template>
    </BasicTree>
    
    <!--右下角按钮-->
    <template #footer>
      <PopConfirmButton title="确定放弃编辑？" @confirm="closeDrawer" okText="确定" cancelText="取消">取消</PopConfirmButton>
      <a-button @click="handleSubmit(false)" type="primary" :loading="loading" ghost style="margin-right: 0.8rem">仅保存</a-button>
      <a-button @click="handleSubmit(true)" type="primary" :loading="loading">保存并关闭</a-button>
    </template>
  </BasicDrawer>
</template>
<script lang="ts" setup>
import {ref, unref} from 'vue';
import {BasicDrawer, useDrawerInner} from '/@/components/Drawer';
import {BasicTree, TreeItem} from '/@/components/Tree';
import {BasicForm, useForm} from '/@/components/Form/index';
import {PopConfirmButton} from '/@/components/Button';
import {listPermissionTree} from '/@/views/system/menu/menu.api'
import {saveOrUpdateTenantPackage} from './tenantPackage.api';
import {listScene} from '/@/views/system/menu/scene/scene.api';
import {formPermissionSchema} from './tenantPackage.data';
import {useMessage} from '/@/hooks/web/useMessage';
import {Icon} from '/@/components/Icon';

const { createMessage } = useMessage();
  //表单配置
  const [registerForm, {setProps, resetFields, setFieldsValue, validate, updateSchema}] = useForm({
    labelWidth: 80,
    labelCol: {
      md: { span: 4 },
      sm: { span: 6 },
    },
    wrapperCol: {
      md: { span: 20 },
      sm: { span: 18 },
    },
    schemas: formPermissionSchema,
    showActionButtonGroup: false,
  });
  // 声明Emits
  const emit = defineEmits(['success', 'register']);
  //树的信息
  const treeData = ref<TreeItem[]>([]);
  //树的全部节点信息
  const allTreeKeys = ref<any>([]);
  //树的选择节点信息
  const checkedKeys = ref([]);
  const defaultCheckedKeys = ref([]);
  //树的选中的节点信息
  const selectedKeys = ref([]);
  const sceneId = ref('')

  //树的实例
  const treeRef = ref(null);
  const loading = ref(false);

  const isUpdate = ref(true);
  const [registerDrawer, {setDrawerProps, closeDrawer}] = useDrawerInner(async (data) => {
    await reset();
    setDrawerProps({confirmLoading: false, loading:true});
    isUpdate.value = !!data?.isUpdate;
    const menuIds = data?.record?.menuIds || []

    if (unref(isUpdate)) {
      //表单赋值
      await setFieldsValue({
        ...data.record,
      });
    }

    updateSchema({
      field: 'sceneId',
      component: 'ApiSelect',
      componentProps: {
        optionFilterProp: "label",
        labelField: 'name',
        valueField: 'id',
        showSearch: true,
        api: listScene,
        onSelect: async (value: any, option: any) => {
          console.log("option", option);
          
          sceneId.value = value
          setDrawerProps({confirmLoading: false, loading:true});
          listPermissionTree({sceneId: sceneId.value}).then(roleResult => {
            treeData.value = roleResult.treeList;
            allTreeKeys.value = roleResult.menuList.map(e => e.id)
            setDrawerProps({loading: false});
          }).catch(e => {
            setDrawerProps({loading: false});
          });
        },
        onOptionsChange: async (options) => {
          if(options && options.length > 0) {
            sceneId.value = options[0].value
            setFieldsValue({sceneId: sceneId.value})
            const roleResult = await listPermissionTree({sceneId: sceneId.value });
            treeData.value = roleResult.treeList;
            allTreeKeys.value = roleResult.menuList.map(e => e.id)
          }
        }
      },
    })

    // 初始化菜单数据
    checkedKeys.value = menuIds;
    defaultCheckedKeys.value = menuIds;
    setDrawerProps({loading:false});
  });

  /**
   * 点击选中
   */
  function onCheck(o) {
    checkedKeys.value = o.checked ? o.checked : o
  }

  /**
   * 数据重置
   */
  function reset() {
     treeData.value = [];
     allTreeKeys.value = [];
     checkedKeys.value = [];
     defaultCheckedKeys.value = [];
     selectedKeys.value = [];
     resetFields()
  }
  /**
   * 获取tree实例
   */
  function getTree() {
    const tree = unref(treeRef);
    if (!tree) {
      throw new Error('tree is null!');
    }
    return tree;
  }
  /**
   * 提交
   */
  async function handleSubmit(exit) {
    try {
      let values = await validate();
      let params = {
        // @ts-ignore
        menuIds:  getTree().getCheckedKeys(),
        lastMenuIds: defaultCheckedKeys.value,
      };
      const from = { ...values, ...params}
      console.log("from", from);
      
      loading.value = true;
      await saveOrUpdateTenantPackage(from, unref(isUpdate));
      exit && closeDrawer()
      //刷新列表
      emit('success');
      createMessage.success("操作成功")
    } finally {
      loading.value = false;
    }
  }
</script>
